<template>
  <div class="split-container">
    <div ref="leftPane" class="split-pane">
      <el-card class="split-pane-card">
        <el-collapse v-model="activeNames">
          <el-collapse-item title="表单组件" name="1">
            <draggable
              v-model="formComponents"
              :clone="clone"
              :group="{ name: 'input', pull: 'clone', put: false }"
            >
              <template #item="{ element }">
                <el-button :key="element.label" style="margin: 5px; border-style: dashed">
                  {{ element.label }}
                </el-button>
              </template>
            </draggable>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>
    <div ref="middlePane" class="split-pane">
      <!-- 中间内容 -->
      <el-card class="split-pane-card">
        <div class="form-split-pane center">
          <el-row
            :gutter="5"
            v-for="(workflowInput, workflowInputIndex) in workflowInputs"
            :key="workflowInputIndex"
            @mouseover="currentRow = workflowInputs[workflowInputIndex]"
            @mouseout="currentRow = null"
          >
            <div class="form-tool" v-show="currentRow == workflowInput">
              <el-icon icon="Delete" :size="13" @click="removeRow(workflowInputIndex)">
                <Delete />
              </el-icon>
            </div>
            <el-col
              v-for="(column, colkey) in workflowInput"
              :key="colkey"
              :span="24 / workflowInput.length"
            >
              <div class="dragg-info" v-if="column.length <= 0">请将组件拖至此处</div>
              <draggable v-model="workflowInputs[workflowInputIndex][colkey]" group="input">
                <template #item="{ element, index }">
                  <div
                    :class="{ 'draggable-item': true, active: element.id == currentInput.id }"
                    :key="element.id"
                    @click="setAttribute(element)"
                  >
                    <WorkflowFormItem :element="column[index]" v-model="element.value" />
                    <div class="form-tool" v-if="element.id == currentInput.id">
                      <el-icon icon="Delete" :size="13" @click="removeComponent">
                        <Delete />
                      </el-icon>
                    </div>
                  </div>
                </template>
              </draggable>
            </el-col>
          </el-row>
          <el-popover placement="bottom" :width="235" trigger="click">
            <template #reference>
              <div class="form-row-btn">
                <el-button icon="Plus" style="border: none">添加一行</el-button>
              </div>
            </template>
            <el-button style="margin-left: 12px; margin-bottom: 5px" @click="oncolumnbtnClick(1)"
              >一行一列</el-button
            >
            <el-button style="margin-bottom: 5px" @click="oncolumnbtnClick(2)">一行两列</el-button>
            <el-button @click="oncolumnbtnClick(3)">一行三列</el-button>
            <el-button @click="oncolumnbtnClick(4)">一行四列</el-button>
          </el-popover>
        </div>
      </el-card>
    </div>
    <div ref="rightPane" class="split-pane">
      <!-- 右侧内容 -->
      <el-card class="split-pane-card">
        <el-form
          :model="currentInput"
          class="attr-form"
          v-if="currentInput.id"
          label-width="auto"
          label-position="top"
        >
          <el-form-item label="标识">
            <el-input v-model="currentInput.id" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="标签">
            <el-input v-model="currentInput.label"></el-input>
          </el-form-item>
          <el-form-item label="字段名">
            <el-input v-model="currentInput.name"></el-input>
          </el-form-item>
          <el-form-item label="长度">
            <el-row>
              <el-col :span="12">
                <el-input
                  v-model="currentInput.maxLength"
                  type="number"
                  placeholder="最大长度"
                ></el-input>
              </el-col>
              <el-col :span="12">
                <el-input
                  v-model="currentInput.minLength"
                  type="number"
                  placeholder="最小长度"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <template #label>
              <span>样式：</span>
              <el-button type="default" class="btn-right" @click="addStyle" icon="Plus"></el-button>
            </template>
            <el-row :gutter="5" v-for="(item, index) in currentInput.styles" :key="index">
              <el-col :span="8">
                <el-input size="small" placeholder="标签" v-model="item.name"></el-input>
              </el-col>
              <el-col :span="8">
                <el-input size="small" placeholder="值" v-model="item.value"></el-input>
              </el-col>
              <el-col :span="8">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeStyle(index)"
                  icon="Delete"
                ></el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="选项" v-if="currentInput.items">
            <el-row :gutter="5" v-for="(item, index) in currentInput.items" :key="index">
              <el-col :span="8">
                <el-input size="small" placeholder="标签" v-model="item.label"></el-input>
              </el-col>
              <el-col :span="8">
                <el-input size="small" placeholder="值" v-model="item.value"></el-input>
              </el-col>
              <el-col :span="8">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeItem(index)"
                  icon="Delete"
                ></el-button>
              </el-col>
            </el-row>
            <el-button
              type="default"
              class="margin-top-10"
              style="width: 100%"
              @click="addItem"
              icon="Plus"
              >添加选项</el-button
            >
          </el-form-item>
          <el-form-item label="数据验证">
            <el-checkbox-group v-model="currentInput.rules">
              <el-checkbox :label="i.name" v-for="(i, key) in formRules" :key="key">{{
                i.label
              }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
// 导入pinia仓库
import pinia from '@/stores';
// 导入工作流小仓储
import useWorkflowStore from '@/stores/modules/workflow';
// 导入split.js
//@ts-ignore
import Split from 'split.js';
// 导入拖拽组件
import draggable from 'vuedraggable';
// 导入表单组件
import WorkflowFormItem from './workflow-form-item.vue';
// 导入el-icon图标
import { Delete } from '@element-plus/icons-vue';
// 导入输入类型
import type { WorkflowInput } from '@/utils/api/workflow/definition/type';

// 当前行
const currentRow = ref<Array<Array<WorkflowInput>> | null>(null);

// 当前输入
const currentInput = ref<WorkflowInput>({
  id: '',
  type: 'text',
  label: '',
  name: '',
  items: [],
  styles: [],
  rules: [],
  minLength: undefined,
  maxLength: undefined
});

// 分割视图实例
// 获取工作流小仓储实例
const workflowStore = useWorkflowStore(pinia);

// 左边容器实例
const leftPane = ref<HTMLDivElement>();
// 中间容器实例
const middlePane = ref<HTMLDivElement>();
// 右边容器实例
const rightPane = ref<HTMLDivElement>();
// 分割视图实例
let splitInstance: Split.Instance;

//折叠板默认展开name
const activeNames = ref(['1']);

// 组件挂载
onMounted(() => {
  initSplit();
});

// 组件卸载
onBeforeUnmount(() => {
  if (splitInstance) {
    splitInstance.destroy();
  }
});

// 初始化split
const initSplit = () => {
  splitInstance = Split([leftPane.value!, middlePane.value!, rightPane.value!], {
    sizes: [20, 60, 20], // 初始比例
    minSize: [200, 200, 200], // 最小尺寸限制
    gutterSize: 8, // 分割线大小
    direction: 'horizontal', // 水平分割
    cursor: 'col-resize', // 光标样式
    onDragEnd: () => {
      // 拖动结束时的回调，可以在此处更新状态或发送事件
    }
  });
};

// 定义props接收父组件传递的对象
const props = defineProps<{
  modelValue: Array<Array<Array<WorkflowInput>>>;
}>();

// 定义 emits 用于向父组件传递更新事件
const emits = defineEmits<{
  (e: 'update:modelValue', data: Array<any>): void;
}>();

// 使用 computed 从 props 创建一个可读写的本地副本，这样可以直接修改它，同时触发更新事件向父组件回传数据(即实现父子组件的数据双向绑定)
const workflowInputs = computed({
  get(): Array<Array<Array<WorkflowInput>>> {
    return props.modelValue;
  },
  set(newValue: Array<Array<Array<WorkflowInput>>>) {
    emits('update:modelValue', newValue);
  }
});

// 表单组件数据
const formComponents = computed(() => {
  return workflowStore.getFormComponents;
});

// 表单组件校验规则
const formRules = computed(() => {
  return workflowStore.getRules;
});

// 自动生成id
const clone = (item: WorkflowInput) => {
  let i = { ...item };
  i.id = Date.now() + Math.random().toString(36).substr(2);
  return i;
};

// 添加行和列
const oncolumnbtnClick = (col: number) => {
  workflowInputs.value.push([]);
  for (let i = 0; i < col; i++) {
    workflowInputs.value[workflowInputs.value.length - 1].push([]);
  }
};

// 删除行
const removeRow = (index: number) => {
  workflowInputs.value.splice(index, 1);
};

// 设置属性
const setAttribute = (item: WorkflowInput) => {
  currentInput.value = item;
};

// 删除组件
const removeComponent = () => {
  workflowInputs.value.forEach((arr: Array<Array<WorkflowInput>>) => {
    let i = -1;
    arr.some((element: Array<WorkflowInput>, r: number) => {
      element.some((input: WorkflowInput, index: number) => {
        if (input.id == currentInput.value.id) {
          i = index;
          return true;
        }
      });
      if (i >= 0) {
        arr[r].splice(i, 1);
        return true;
      }
    });
  });
};

// 删除样式选项
const removeStyle = (index: number) => {
  currentInput.value.styles?.splice(index, 1);
};

// 添加样式选项
const addStyle = () => {
  if (!currentInput.value.styles) {
    currentInput.value.styles = [];
  }
  currentInput.value.styles.push({ name: '', value: '' });
};

// 删除选项
const removeItem = (index: number) => {
  currentInput.value.items?.splice(index, 1);
};

// 添加选项
const addItem = () => {
  if (!currentInput.value.items) {
    currentInput.value.items = [];
  }
  currentInput.value.items.push({ label: '', value: '' });
};
</script>

<style scoped lang="scss">
.margin-top-10 {
  margin-top: 10px;
}

.split-container {
  display: flex;

  .split-pane {
    overflow: auto;
    .split-pane-card {
      min-height: $work_flow_min_height;
    }
    .form-row-btn {
      text-align: center;
      margin-top: 20px;
    }

    .form-split-pane.center .el-row {
      padding: 5px;
      margin: 5px 0;

      .el-col {
        border: 1px dotted #ddd;
      }

      &.el-row:hover,
      &.el-row.active {
        border: 1px dotted #ff9900;
      }

      .dragg-info {
        text-align: center;
        width: 100%;
        height: 30px;
        line-height: 30px;
        color: #ccc;
      }

      .form-tool {
        position: absolute;
        right: -1px;
        bottom: -1px;
        background: #ff9900;
        z-index: 1;
        color: white;
        cursor: pointer;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        font-size: 12px;
        font-weight: bold;
      }

      .draggable-item {
        position: relative;
        padding: 10px;
        background: #fff;
        cursor: move;
        border: 2px solid #fff;

        .form-tool {
          background: #409eff;
          right: -2px;
          bottom: -2px;
        }

        &:hover,
        &.active {
          border: 2px solid #409eff;
          background: rgba(235, 245, 255, 0.5);
        }
      }
    }

    .attr-form {
      .el-form-item {
        position: relative;

        .btn-right {
          position: absolute;
          padding: 0px 5px;
          top: -5px;
          right: 0px;
        }
      }
    }
  }

  //:deep深度选择器
  :deep(.gutter) {
    border: 1px solid #ccc;
    background-color: #eee;
    border-radius: 30px;
    display: flex;
    align-items: center;
    /* 垂直居中 */
    justify-content: center;
    /* 水平居中（如果需要） */
    flex-direction: column;
    /* 垂直排列 */

    &:hover {
      cursor: col-resize;
    }

    &::before,
    &::after {
      content: '';
      display: block;
      width: 8px;
      height: 6px;
      border-top: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
      margin-top: 2px;
      margin-bottom: 2px;
    }
  }
}
</style>
